<template>
  <div class="chart-download" @click="convertCanvasToImage">
    <i class="iconfont icon-cloud-download"></i>
    下载图片
  </div>
</template>
<script>
import { computed, watch, ref, onMounted, nextTick } from 'vue'
import { useChartDownloadData } from '@src/modules/report/managementReport/charts/components/useChartData'
import Platform from '@src/util/platform.ts'

export default {
  name: 'chart-download',
  props: {
    id: {
      type: String,
      default: ''
    },
    chartType: {
      type: String,
      default: ''
    },
    chartData: {
      type: Array,
      default: () => []
    },
    // 判断一个页面多个图表的情况
    type: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {

    const init = async() => {
      let result = null
      try {
         await nextTick(() => {
          const nodata = document.querySelector('.stats-chart-empty')
          const display = window.getComputedStyle(nodata, null)['display']
          if (display === 'none') {
            result = true
          } else {
            result = false
          }
        })
      } catch(error) {
        console.log(error)
      }
      return result
    }

    const convertCanvasToImage = async() => {
      await nextTick(async() => {
        let result = false;
        if(props.chartType === 'spare-part-sale'){
          result = props?.chartData?.length > 0 || false;
        }else{
          result = await init();
        }
        if (!result) return Platform.alert('请在有数据状态下进行下载！') // 暂无数据 禁止下载
        
        const { chartDomId, chartDownloadName } = useChartDownloadData(props.chartType, props.type)
        const id = props.id || chartDomId
        const canvas = document.querySelector(`#${id} div canvas`)
        console.log(canvas,'canvas')
        const img = canvas.toDataURL('image/png');
        const oA = document.createElement('a');
        oA.download = chartDownloadName// 设置下载的文件名，默认是'下载'
        oA.href = img;
        document.body.appendChild(oA);
        oA.click();
        oA.remove();
      })
    }

    return {
      convertCanvasToImage
    }
  }
}
</script>
<style lang="scss" scoped>
.chart-download {
  width: 80px;
  font-size: 14px;
  color: #606266;
  cursor: pointer;
  &:hover {
    color: $color-primary-light-6;
  }
}
</style>